package com.tancw.cloud.auth.controller;

import com.tancw.cloud.common.Result;
import com.tancw.cloud.common.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping
public class AuthController {

    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestBody Map<String, String> loginReq) {
        String username = loginReq.get("username");
        String password = loginReq.get("password");

        log.info("用户登录: {}", username);

        // 简化演示，实际应该调用用户服务验证
        if ("admin".equals(username) && "123456".equals(password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", 1L);
            claims.put("username", username);

            String token = JwtUtil.generateToken(claims);

            Map<String, String> result = new HashMap<>();
            result.put("token", token);
            result.put("username", username);

            return Result.success(result);
        }

        return Result.fail("用户名或密码错误");
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody Map<String, String> registerReq) {
        String username = registerReq.get("username");
        log.info("用户注册: {}", username);
        
        // 实际应该调用用户服务注册
        return Result.success("注册成功");
    }

    @GetMapping("/validate")
    public Result<Map<String, Object>> validate(@RequestHeader("Authorization") String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            if (JwtUtil.isTokenExpired(token)) {
                return Result.fail("Token已过期");
            }

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", JwtUtil.getUserId(token));
            userInfo.put("username", JwtUtil.getUsername(token));

            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.fail("Token无效");
        }
    }
}
